<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input size="mini" v-model="listQuery.categoryName" clearable class="filter-item" style="width: 200px;"
        placeholder="请输入行业名称" />
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找
      </el-button>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" border :data="list" size="mini" element-loading-text="正在查询中。。。"
      highlight-current-row>

      <el-table-column align="left" label="课程名称" prop="categoryName" width="260px">
        <template slot-scope="scope">
          <span style="color:#1679FB;font-size: 14px;font-weight: bold;">
            {{scope.row.categoryName}}
          </span>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="价格" prop="price" width="100px"/> -->

      <el-table-column align="center" label="状态" prop="associatedStatus" width="100px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.associatedStatus===1" type="success">上架</el-tag>
          <el-tag v-if="scope.row.associatedStatus===2" type="info">下架</el-tag>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" label="创建时间" prop="createDate"/>-->
      <el-table-column align="center" label="操作" width="350" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button style="width:20%;" v-if="scope.row.associatedStatus===2" type="success" size="mini"
            @click="handleStatus(scope.row,1)">上架课程</el-button>
          <el-button style="width:20%;" v-if="scope.row.associatedStatus===1" type="info" size="mini"
            @click="handleStatus(scope.row,2)">下架课程</el-button>
          <el-button style="width:20%;" type="primary" size="mini" @click="handleCourseManage(scope.row)">课程管理
          </el-button>
          <el-button style="width:20%;" type="success" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <!--<el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>-->

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px"
        style="width: 400px; margin-left:50px;">

        <el-form-item label="选择行业" prop="categoryId">
          <el-select v-model="dataForm.categoryId" filterable placeholder="请选择" @change="selectCateory">
            <el-option v-for="item in industryList" :key="item.id" :label="item.categoryName" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="课时单价" prop="price">
          <el-input v-model="dataForm.price" type="number"/>
        </el-form-item> -->
        <el-form-item label="状态" prop="associatedStatus">
          <el-select v-model="dataForm.associatedStatus" clearable placeholder="请选择">
            <el-option :value="1" label="上架" />
            <el-option :value="2" label="下架" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
        <el-button size="mini" v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button size="mini" v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>

<script>
  import {
    listAssociatedIndustry,
    updateAssociatedIndustry,
    createAssociatedIndustry,
    deleteAssociatedIndustry,
    typeAssociatedIndustry
  } from '@/api/associatedIndustry'
  import {
    uploadPath
  } from '@/api/storage'
  import {
    getToken
  } from '@/utils/auth'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

  export default {
    name: 'AssociatedIndustry',
    components: {
      Pagination
    },
    data() {
      return {
        uploadPath,
        industryList: undefined,
        updateParam: undefined,
        list: undefined,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          categoryId: undefined,
          categoryName: undefined,
          sort: 'create_date',
          order: 'desc'
        },
        dataForm: {
          id: undefined,
          categoryId: undefined,
          categoryName: undefined,
          price: undefined,
          associatedStatus: undefined,
          deleteMark: undefined,
          createDate: undefined
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          categoryId: [{
            required: true,
            message: '行业不能为空',
            trigger: 'blur'
          }],
          price: [{
            required: true,
            message: '课程单价不能为空',
            trigger: 'blur'
          }]
        },
        downloadLoading: false
      }
    },
    computed: {
      headers() {
        return {
          'X-Litemall-Admin-Token': getToken()
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      selectCateory (e) {
        this.industryList.filter(res => {
          if (e === res.id) {
            this.dataForm.categoryName = res.categoryName
            return
          }
        })
      },
      getList() {
        this.listLoading = true
        listAssociatedIndustry(this.listQuery)
          .then(response => {
            this.list = response.data.data.items
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.list = []
            this.total = 0
            this.listLoading = false
          })
      },
      getIndustryList() { // 得到类目列表
        typeAssociatedIndustry()
          .then(response => {
            this.industryList = response.data.data
          })
          .catch(() => {
            this.industryList = []
          })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetForm() {
        this.dataForm = {
          id: undefined,
          categoryId: undefined,
          categoryName: undefined,
          price: undefined,
          associatedStatus: 1,
          deleteMark: undefined,
          createDate: undefined
        }
      },
      handleStatus(parm, status) {
        this.updateParam = Object.assign({}, parm)
        this.updateParam.associatedStatus = status
        let content = ''
        if (status === 1) {
          content = '是否上架课程？'
        } else if (status === 2) {
          content = '是否下降课程？'
        } else {
          content = '是否拒绝该用户的申请！！'
        }
        this.$confirm(content, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (status === 0) {
            updateAssociatedIndustry(this.updateParam)
              .then(() => {
                this.$notify.success({
                  title: '成功',
                  message: '课程已下架'
                })
                // 刷新列表数据
                this.getList()
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.message
                })
                // 刷新列表数据
                this.getList()
              })
          } else if (status === 1) {
            updateAssociatedIndustry(this.updateParam)
              .then(() => {
                this.$notify.success({
                  title: '成功',
                  message: '课程已下架'
                })
                // 刷新列表数据
                this.getList()
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.message
                })
                // 刷新列表数据
                this.getList()
              })
          } else {
            updateAssociatedIndustry(this.updateParam)
              .then(() => {
                this.$notify.success({
                  title: '成功',
                  message: '审核已拒绝'
                })
                // 刷新列表数据
                this.getList()
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.message
                })
                // 刷新列表数据
                this.getList()
              })
          }
        }).catch(() => {
          this.getList()
        })
      },
      handleCreate() {
        this.resetForm()
        this.getIndustryList()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      uploadPicUrl: function(response) {
        this.dataForm.picUrl = response.data.url
      },
      createData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            createAssociatedIndustry(this.dataForm)
              .then(response => {
                this.list.unshift(response.data.data)
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '创建成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.message
                })
              })
          }
        })
      },
      handleUpdate(row) {
        this.getIndustryList()
        this.dataForm = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            updateAssociatedIndustry(this.dataForm)
              .then(() => {
                for (const v of this.list) {
                  if (v.id === this.dataForm.id) {
                    const index = this.list.indexOf(v)
                    this.list.splice(index, 1, this.dataForm)
                    break
                  }
                }
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.message
                })
              })
          }
        })
      },
      handleDelete(row) {
        deleteAssociatedIndustry(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.message
            })
          })
      },
      handleCourseManage(row) {
        this.$router.push({
          path: '/courseManage/queryCourse',
          query: {
            associatedIndustryId: row.id,
            categoryId: row.categoryId,
            categoryName: row.categoryName
          }
        })
      }
    }
  }
</script>
